package com.techsoul.module.pms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.collection.MapUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.pms.enmus.ErrorType;
import com.techsoul.module.pms.mapper.PmsBirdWatchMapper;
import com.techsoul.module.pms.mapper.PmsBirdWatchSumMapper;
import com.techsoul.module.pms.pojo.entity.PmsBirdWatch;
import com.techsoul.module.pms.pojo.entity.PmsBirdWatchSum;
import com.techsoul.module.pms.pojo.param.PmsBirdWatchSaveParam;
import com.techsoul.module.pms.pojo.param.PmsBirdWatchSearchParam;
import com.techsoul.module.pms.pojo.param.PmsBirdWatchSumSearchParam;
import com.techsoul.module.pms.pojo.vo.PmsBirdWatchVo;
import com.techsoul.module.pms.service.IPmsBirdWatchService;
import com.techsoul.module.system.mapper.OperationLogMapper;
import com.techsoul.module.system.pojo.entity.OperationLog;
import com.techsoul.module.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 鸟类观测识别统计 Service实现
 *
 * @author liuen
 * @date 2021-12-08
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class PmsBirdWatchServiceImpl implements IPmsBirdWatchService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private IConfigService configService;

    @Autowired
    private PmsBirdWatchMapper mapper;
    @Autowired
    private PmsBirdWatchSumMapper pmsBirdWatchSumMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private OperationLogMapper operationLogMapper;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(PmsBirdWatchSaveParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        PmsBirdWatch entity = new PmsBirdWatch();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "");
        entity.setCreateBy(sysUser.getId()) ;
        entity.setUpdateBy(sysUser.getId()) ;
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        this.mapper.insert(entity);
        PmsBirdWatchSumSearchParam pmsBirdWatchSearchParam = new PmsBirdWatchSumSearchParam();
        pmsBirdWatchSearchParam.setBirdName(params.getBirdName());
        PmsBirdWatchSum pmsBirdWatchSum = pmsBirdWatchSumMapper.findByBirdName(pmsBirdWatchSearchParam);
        if(pmsBirdWatchSum!=null){
            int totalCt=0;
            if(pmsBirdWatchSum.getTotalCt()!=null){
                totalCt=  pmsBirdWatchSum.getTotalCt();

            }

            pmsBirdWatchSum.preUpdate(sysUser.getId());
            pmsBirdWatchSum.setTotalCt(totalCt+params.getTodayCt());
            pmsBirdWatchSumMapper.updateById(pmsBirdWatchSum);
        }else{
            PmsBirdWatchSum newpbw = new PmsBirdWatchSum();
            BeanUtils.copyProperties(entity, newpbw);
            newpbw.setId(idWorker.nextId() + "");
            newpbw.setCreateBy(sysUser.getId()) ;
            newpbw.setUpdateBy(sysUser.getId()) ;
            newpbw.setCreateTime(new Date());
            newpbw.setUpdateTime(new Date());
            this.pmsBirdWatchSumMapper.insert(newpbw);
        }
        return entity.getId();
    }

    /**
     *海康自动识别
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer insertByHaikang(PmsBirdWatchSaveParam params) {
        // UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        PmsBirdWatch entity = new PmsBirdWatch();
        String today = DateUtils.formatDate(new Date());
        params.setCtDate(today);
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert("1");


        if(!StringUtils.isNull(params.getBirdName())){
            PmsBirdWatchSearchParam pmsBirdWatchSearchParam  =new PmsBirdWatchSearchParam();

            pmsBirdWatchSearchParam.setCtDate(params.getCtDate());
            if(params.getBirdName().equals("c9a057b3c9100001e3869690f7f03f00c9a057b3c910000168de50401140cd2")){
                pmsBirdWatchSearchParam.setBirdName("黑脸琵鹭");
            }else{
                pmsBirdWatchSearchParam.setBirdName(params.getBirdName());
            }
            List<PmsBirdWatch> PmsBirdWatchVos  = this.mapper.findByBirdName(pmsBirdWatchSearchParam);

            if(PmsBirdWatchVos!=null&&PmsBirdWatchVos.size()>0){
                PmsBirdWatch entityFromDb=(PmsBirdWatch)PmsBirdWatchVos.get(0);
                int todayCt=0;
                int totalCt=0;
                if(entityFromDb.getTotalCt()!=null){
                    totalCt=  entityFromDb.getTotalCt();

                }
                if(entityFromDb.getTodayCt()!=null){
                    todayCt=  entityFromDb.getTodayCt();

                }
                entityFromDb.preUpdate("1");

                entity.setTodayCt(todayCt+params.getTodayCt());
                entity.setTotalCt(totalCt+params.getTodayCt());
                this.mapper.insert(entity);

                //this.mapper.updateById(entityFromDb);

            }else{
                entity.setTodayCt(params.getTodayCt());
                entity.setTotalCt(params.getTodayCt());
                this.mapper.insert(entity);

            }
            PmsBirdWatchSumSearchParam pmsBirdWatchSumSearchParam = new PmsBirdWatchSumSearchParam();
            pmsBirdWatchSumSearchParam.setBirdName(params.getBirdName());
            PmsBirdWatchSum pmsBirdWatchSum = pmsBirdWatchSumMapper.findByBirdName(pmsBirdWatchSumSearchParam);
            if(pmsBirdWatchSum!=null){
                int totalCt=0;
                if(pmsBirdWatchSum.getTotalCt()!=null){
                    totalCt=  pmsBirdWatchSum.getTotalCt();

                }

                pmsBirdWatchSum.preUpdate("1");
                pmsBirdWatchSum.setTotalCt(totalCt+params.getTodayCt());
                pmsBirdWatchSumMapper.updateById(pmsBirdWatchSum);
            }else{
                PmsBirdWatchSum newpbw = new PmsBirdWatchSum();
                BeanUtils.copyProperties(entity, newpbw);
                newpbw.setId(idWorker.nextId() + "");
                newpbw.setCreateBy("1") ;
                newpbw.setUpdateBy("1") ;
                newpbw.setCreateTime(new Date());
                newpbw.setUpdateTime(new Date());
                this.pmsBirdWatchSumMapper.insert(newpbw);
            }
            return 0;
        }
        else{
            this.mapper.insert(entity);
            return 0;
        }
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(PmsBirdWatchSaveParam params) {
        PmsBirdWatch entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(sysUser.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public PmsBirdWatchVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<PmsBirdWatchVo> findAll(PmsBirdWatchSearchParam params) {
        return this.mapper.findAll(params);
    }
    /**
     * 统计列表
     * @param params
     * @return
     */
    @Override
    public List<PmsBirdWatchVo> countBirdStats(PmsBirdWatchSearchParam params) {
        return this.mapper.countBirdStats(params);
    }

    /**
     * 统计数量
     * @param params
     * @return
     */
    @Override
    public Integer countTotalBird(PmsBirdWatchSearchParam params) {
        return this.mapper.countTotalBird(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<PmsBirdWatchVo> findAll(PmsBirdWatchSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }
    @Override
    public PmsBirdWatchVo removeSpecialChar(PmsBirdWatchVo input){

        Pattern p =null;
        Matcher m = null;;
        String rt = "";

        if(!StringUtils.isNull(input.getBirdName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getBirdName());
            rt = m.replaceAll("");
            rt=rt.trim();
            input.setBirdName(rt);
        }
        if(!StringUtils.isNull(input.getCtDate())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCtDate());
            rt = m.replaceAll("");
            rt=rt.trim();
            input.setCtDate(rt);
        }
        if(!StringUtils.isNull(input.getBirdCategory())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getBirdCategory());
            rt = m.replaceAll("");
            rt=rt.trim();
            input.setBirdCategory(rt);
        }

        if(!StringUtils.isNull(input.getCameraLoc())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCameraLoc());
            rt = m.replaceAll("");
            rt=rt.trim();
            input.setCameraLoc(rt);
        }

        if(!StringUtils.isNull(input.getCameraId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCameraId());
            rt = m.replaceAll("");
            rt=rt.trim();
            input.setCameraId(rt);
        }





        return input;
    }
    /**
     * 导入模板
     */
    @Override
    public String importTemplate() {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "导入模板-鸟类观测数字.xlsx";
        try {
            new ExcelExport(null, PmsBirdWatchVo.class).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("生成鸟类观测数字导入模板失败", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }
    /**
     * 导入
     * @param file
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String importData(Date applyDate, String area,MultipartFile file) {
        List<PmsBirdWatchVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(PmsBirdWatchVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }
        int line = 0;
        for (PmsBirdWatchVo data : dataList) {
            data = this.removeSpecialChar(data);
            line++;

            if(data.getTodayManualCt()==null){
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.BIRDWATCHIMPORT.getStatusName());
                operationLog.setErrorMsg("没有具体数字");

                operationLog.setLocation("第"+line+"行");
                operationLog.setMethod("导入模板-鸟类观测数字");
                operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);//add log
                logNum++;
                continue;
            }else{
                if(!StringUtils.isNumeric(data.getTodayManualCt())){
                    //add log
                    OperationLog operationLog =new OperationLog();
                    operationLog.setOperationType(ErrorType.BIRDWATCHIMPORT.getStatusName());
                    operationLog.setErrorMsg("鸟类数目格式不对");
                    operationLog.setLocation("第"+line+"行");
                    operationLog.setMethod("导入模板-鸟类观测数字");
                    operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
                    if (user != null) {
                        operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                    }
                    operationLogMapper.insert(operationLog);//add log
                    logNum++;
                    continue;
                }
            }
            if(StringUtils.isNull(data.getBirdName())){
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.BIRDWATCHIMPORT.getStatusName());
                operationLog.setErrorMsg("鸟类名称没有提供");
                operationLog.setLocation("第"+line+"行");
                operationLog.setMethod("导入模板-鸟类观测数字");
                operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);
                logNum++;
                continue;
            }

            try {
                PmsBirdWatchSaveParam saveParam = new PmsBirdWatchSaveParam();
                BeanUtils.copyProperties(data, saveParam);
                saveParam.setCtDate(DateUtils.formatDate(applyDate));
                if(!StringUtils.isNull(data.getTodayManualCt())){
                    saveParam.setTodayCt(Double.valueOf(data.getTodayManualCt()).intValue());
                    saveParam.setTodayManualCt(Double.valueOf(data.getTodayManualCt()).intValue());
                }

                saveParam.setArea(area);
                this.insert(saveParam);

                successNum++;
                successMsg.append("<br/>" + successNum + "导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "导入失败：";
                failureMsg.append(msg + e.getMessage());
                //add log table
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.BIRDWATCHIMPORT.getStatusName());
                operationLog.setErrorMsg(failureMsg.toString());
                operationLog.setLocation("第"+line+"行");
                operationLog.setMethod("导入模板-鸟类观测数字");
                operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.BIRDWATCHIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setLocation("第"+line+"行");
            operationLog.setMethod("导入模板-鸟类观测数字");
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            throw new ExcelException(failureMsg.toString());
        } else {
            if(logNum>0){
                successMsg.insert(0, "恭喜您，操作成功！共 " + successNum + " 条，另有：" +logNum+ " 条数据不能正常导入，已写入日志");

            }else{
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

            }
        }
        return successMsg.toString();
    }

    @Override
    public String exportData(PmsBirdWatchSearchParam params) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "鸟类观测-"+params.getCtDate().replace("-", "")+ "-"+DateUtils.getDate("yyyyMMdd")+".xlsx";

        List<PmsBirdWatchVo> list = this.findAll(params);
        try {
            new ExcelExport(null, PmsBirdWatchVo.class).setDataList(list).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("鸟类观测", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }
    /**
     * 统计柱状图
     *
     * @return
     */
    @Override
    public Map<String, Object> countBarData() {
        Map<String, Object> map = MapUtils.newHashMap();
        List<PmsBirdWatchVo> pmsBirdWatchVos = this.mapper.countBarData();
        if (ListUtils.isNotEmpty(pmsBirdWatchVos)) {
            List<String> birdTypes = pmsBirdWatchVos.stream().map(pmsBirdWatchVo -> pmsBirdWatchVo.getBirdName()).collect(Collectors.toList());
            List<Integer> manuCt = pmsBirdWatchVos.stream().map(pmsBirdWatchVo -> pmsBirdWatchVo.getSumTodayManualCt()).collect(Collectors.toList());
            List<Integer> allCt = pmsBirdWatchVos.stream().map(pmsBirdWatchVo -> pmsBirdWatchVo.getSumTotal()).collect(Collectors.toList());
            map.put("birdTypes", birdTypes);
            map.put("allCt", allCt);
            map.put("manuCt", manuCt);
        }
        return map;
    }
}
